package com.power.web.action.project;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Vector;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import org.springframework.beans.factory.annotation.Autowired;

import com.power.model.funding.RzMoneyside;
import com.power.Constants;
import com.power.model.funding.RzMoneyside;
import com.power.model.group.TiGroup;
import com.power.model.project.RzProject;
import com.power.services.project.RzProjectService;
import com.power.util.CharacterUtil;
import com.power.util.DateJsonValueProcessor;
import com.power.util.DateTimeUtil;
import com.power.util.FileUtil;
import com.power.util.PageUtil;
import com.power.util.RequestUtil;
import com.power.util.RequestUtil;
import com.power.util.XmlUtil;
import com.power.web.action.base.AbstractBaseAction;

public class RzProjectAction extends AbstractBaseAction {

	private RzProject obj;
	private File imgFile;
	private String imgFileFileName;
   
	private String financingType;
	private PageUtil pu;
	private int pageNo;
	private List<RzProject> recommendList;
	private List<RzProject> hotList;
	private List<RzProject> showList;
	private String jsonString;

	@Autowired
	private RzProjectService service;
	
	public String showPage() {
		try {
			Integer oRid = RequestUtil.getParam(request, "oRid", 0);
			if(oRid==0){
			}else{
				obj = service.read(oRid);
			}
		} catch (Exception e) {
			log.error("获取数据错误");
			e.printStackTrace();
		}
		return "addProjectPage";
	}
	
	public String save() {
		this.response.reset();
		this.response.setCharacterEncoding("UTF-8");
		
			if (null != imgFile) {
				String basePath = request.getSession().getServletContext()
						.getRealPath("/");
				String compressPath = XmlUtil.getValue("filePath",
						"sysConfig")
						+ "/";
				String fileName = "";
				fileName = new Date().getTime()
						+ imgFileFileName.substring(imgFileFileName
								.lastIndexOf("."));
				if (FileUtil.doUpFile(basePath + compressPath + fileName,
						imgFile)) {
					obj.setAttachmentSrc(compressPath + fileName);
				}
			}
		
			if (null != obj) {
				obj.setUpdateTime(DateTimeUtil.getCurrentDateTime());
			}
			
			PrintWriter out = null;
			response.setContentType("text/html;charset=utf-8");
			try {
				out = response.getWriter();
				service.create(obj);
				out.write("<script>parent.saveResult('y');</script>");
			} catch (Exception e) {
				out.write("<script>parent.saveResult('n');</script>");
				e.printStackTrace();
			}
		return null;
	}
	public String buildJSONString(){
		Map<String,String> map = paramMap();
		String callback = this.callback;
		int start = this.start;
		int limit = this.limit;
		if (limit == 0) {
			limit = 20;
		}
		List<RzProject> list = null;
		StringBuffer _JSONStr = new StringBuffer();
		try {
			list = service.findALLbyParam(map,start,limit);
			_JSONStr.append(callback).append("({\"total\":").append(list.size())
					.append(",\"results\":");
			JsonConfig cfg = new JsonConfig();
			cfg.registerJsonValueProcessor(java.util.Date.class,
					new DateJsonValueProcessor("yyyy-MM-dd"));
			cfg.registerJsonValueProcessor(java.sql.Date.class,
					new DateJsonValueProcessor("yyyy-MM-dd"));
			JSONArray jsonObject = JSONArray.fromObject(list, cfg);
			_JSONStr.append(jsonObject.toString());
			_JSONStr.append("})");
		} catch (Exception e) {
			jsonString = "[]";
		}
		jsonString = _JSONStr.toString();
		return Constants.JSONSTRING_RESULT_NAME;
	}
	
	/**
	 * 
	 * @return
	 */
	public String showProject() {
		try {
			limit = 10;
			if(financingType==null){
				financingType = "项目融资";
				List<RzProject> list1 = service.findlist(limit, financingType);
				financingType = "资产交易";
				List<RzProject> list2 = service.findlist(limit, financingType);
				financingType = "政府招商";
				List<RzProject> list3 = service.findlist(limit, financingType);
				financingType = "投资理财";
				limit = 40-list1.size()-list2.size()-list3.size();
				List<RzProject> list4 = service.findlist(limit, financingType);
				List<RzProject> list = new ArrayList<RzProject>();
				for(RzProject obj:list1){
					list.add(obj);
				}for(RzProject obj:list2){
					list.add(obj);
				}for(RzProject obj:list3){
					list.add(obj);
				}for(RzProject obj:list4){
					list.add(obj);
				}
				
				//重新打乱
				Vector<Integer> v=new Vector<Integer>();
				Random r=new Random();
				boolean b=true;
				while(b){
				int i=r.nextInt(list.size());
				if(!v.contains(i))
				v.add(i);
				if(v.size()==list.size())
				b=false;
				}
				showList = new ArrayList<RzProject>(); 
				for(int j=0;j<list.size();j++)
				{
					showList.add(list.get(v.get(j)));
				}
				
			}else{
			   limit= 40;
			   if(financingType.equals("1")){
				   financingType = "项目融资";
			   }else if(financingType.equals("2")){
				   financingType = "资产交易";
			   }else if(financingType.equals("3")){
				   financingType = "政府招商";
			   }else if(financingType.equals("4")){
				   financingType = "投资理财";
			   }
			   showList = service.findlist(limit, financingType);
			}
			
			recommendList = service.findRecommend();
			hotList = service.findHot();
		} catch (Exception e) {
			log.error("显示资方出错", e);
		}
		return "project_result";
	}
	
	public String read() {
		int id = RequestUtil.getParam(this.request, "id", -1);
		obj = this.service.read(new Integer(id));
		hotList = service.findHot();
		return "showProject";
	}
	
	
	private Map<String,String> paramMap(){
		Map<String,String> map = new HashMap<String,String>();
		String orgId = RequestUtil.getParam(request, "orgId", "");
		String checkStatus = RequestUtil.getParam(request, "checkStatus", "");
		String paperTitle = RequestUtil.getParam(request, "paperTitle", "");
		String paperTimeBeginDate = RequestUtil.getParam(request, "paperTimeBeginDate", "");
		String paperTimeEndDate = RequestUtil.getParam(request, "paperTimeEndDate", "");
		String queryLocalFlag = RequestUtil.getParam(request, "queryLocalFlag", "");
		String yearComboStr = RequestUtil.getParam(request, "yearComboStr", "");
		map.put("orgId", orgId);
		map.put("queryLocalFlag", queryLocalFlag);
		map.put("checkStatus", checkStatus);
		map.put("paperTitle", paperTitle);
		map.put("paperTimeBeginDate", paperTimeBeginDate);
		map.put("paperTimeEndDate", paperTimeEndDate);
		map.put("forAudit", RequestUtil.getParam(request, "forAudit", "false"));
		map.put("gbLevel", RequestUtil.getParam(request, "gbLevel", ""));
		map.put("yearComboStr", yearComboStr);

		return map;
	}
	//删除
	  public String delete() {
		String id = RequestUtil.getParam(this.request, "deleteID", "");
		String[] ids = id.split("_");
		try {
			this.response.setCharacterEncoding("UTF-8");
			for (int i = 0; i < ids.length; i++) {
				RzProject group = service.read(new Integer(ids[i]));
				service.delete(group);
			}
			this.response.getWriter().print("{success:true,msg:'删除成功!'}");
		} catch (Exception e) {
			log.error("输出JSON数据错误！", e);
			try {
				this.response.getWriter().print("{failure:true,msg:'删除失败!'}");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}
//推荐
	  public String onTui() {
			String id = RequestUtil.getParam(this.request, "deleteID", "");
			String[] ids = id.split("_");
			try {
				this.response.setCharacterEncoding("UTF-8");
				for (int i = 0; i < ids.length; i++) {
					RzProject group = service.read(new Integer(ids[i]));
					group.setRecommend("0");
					service.update(group);
				}
				this.response.getWriter().print("{success:true,msg:'操作成功!'}");
			} catch (Exception e) {
				log.error("输出JSON数据错误！", e);
				try {
					this.response.getWriter().print("{failure:true,msg:'操作失败!'}");
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			return null;
		}
	  //不推荐
	  public String onNoTui() {
			String id = RequestUtil.getParam(this.request, "deleteID", "");
			String[] ids = id.split("_");
			try {
				this.response.setCharacterEncoding("UTF-8");
				for (int i = 0; i < ids.length; i++) {
					RzProject group = service.read(new Integer(ids[i]));
					group.setRecommend("1");
					service.update(group);
				}
				this.response.getWriter().print("{success:true,msg:'操作成功!'}");
			} catch (Exception e) {
				log.error("输出JSON数据错误！", e);
				try {
					this.response.getWriter().print("{failure:true,msg:'操作失败!'}");
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			return null;
		}
		//热门
	  public String onHot() {
			String id = RequestUtil.getParam(this.request, "deleteID", "");
			String[] ids = id.split("_");
			try {
				this.response.setCharacterEncoding("UTF-8");
				for (int i = 0; i < ids.length; i++) {
					RzProject group = service.read(new Integer(ids[i]));
					group.setIsHot("0");
					service.update(group);
				}
				this.response.getWriter().print("{success:true,msg:'操作成功!'}");
			} catch (Exception e) {
				log.error("输出JSON数据错误！", e);
				try {
					this.response.getWriter().print("{failure:true,msg:'操作失败!'}");
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			return null;
		}
	//取消热门
	  public String onNoHot() {
			String id = RequestUtil.getParam(this.request, "deleteID", "");
			String[] ids = id.split("_");
			try {
				this.response.setCharacterEncoding("UTF-8");
				for (int i = 0; i < ids.length; i++) {
					RzProject group = service.read(new Integer(ids[i]));
					group.setIsHot("1");
					service.update(group);
				}
				this.response.getWriter().print("{success:true,msg:'操作成功!'}");
			} catch (Exception e) {
				log.error("输出JSON数据错误！", e);
				try {
					this.response.getWriter().print("{failure:true,msg:'操作失败!'}");
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			return null;
		}  
	public RzProject getObj() {
		return obj;
	}

	public void setObj(RzProject obj) {
		this.obj = obj;
	}

	public File getImgFile() {
		return imgFile;
	}

	public void setImgFile(File imgFile) {
		this.imgFile = imgFile;
	}

	public String getImgFileFileName() {
		return imgFileFileName;
	}

	public void setImgFileFileName(String imgFileFileName) {
		this.imgFileFileName = imgFileFileName;
	}

	public String getFinancingType() {
		return financingType;
	}

	public void setFinancingType(String financingType) {
		this.financingType = financingType;
	}

	public PageUtil getPu() {
		return pu;
	}

	public void setPu(PageUtil pu) {
		this.pu = pu;
	}

	public int getPageNo() {
		return pageNo;
	}

	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}

	public RzProjectService getService() {
		return service;
	}

	public void setService(RzProjectService service) {
		this.service = service;
	}

	public List<RzProject> getRecommendList() {
		return recommendList;
	}

	public void setRecommendList(List<RzProject> recommendList) {
		this.recommendList = recommendList;
	}

	public List<RzProject> getHotList() {
		return hotList;
	}

	public void setHotList(List<RzProject> hotList) {
		this.hotList = hotList;
	}

	public String getJsonString() {
		return jsonString;
	}

	public void setJsonString(String jsonString) {
		this.jsonString = jsonString;
	}

	public List<RzProject> getShowList() {
		return showList;
	}

	public void setShowList(List<RzProject> showList) {
		this.showList = showList;
	}
	
}
